<template>
  <div class="chat-container">
    <!-- 欢迎界面 -->
    <div class="chat-messages client-chat" v-if="isWelcome">
      <div class="header-bubble">
        <div class="bubble-container">
          <div class="gif-container">
            <img src="/img/avatar.jpg" alt="卡通人物">
          </div>

          <div class="welcome-content">
            <div class="welcome-title">Hi！我是AI助手，很高兴为您服务~</div>
            <div class="welcome-txt">
              我专注于提供AI领域的专业咨询服务，请问您需要了解哪方面的AI问题，我将为您提供相关解答以供参考。
            </div>
            <div class="suggestions-title">您可以这样问一问~</div>

            <div class="suggestions">
              <div class="suggestion" v-for="item in suggestionList" @click="askByReference(item.value)">
                <i :class="item.icon"></i>
                <div>{{ item.name }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages client-chat" v-else>
      <!-- 时间戳 -->
      <div class="timestamp"
        v-if="index === 0 || (index !== 0 && item.timestamp && (Number(item.timestamp) - Number(msgList[index - 1].timestamp)) > timestampGap)"
        v-for="(item, index) in msgList" :key="'timestamp-' + index">
        {{ moment(new Date(String(item.timestamp).length === 10 ? item.timestamp * 1000 : Number(item.timestamp))).format('yyyy-MM-DD HH:mm') }}
      </div>

      <!-- 用户消息 -->
      <div class="message user-message" v-if="item.is_from_self" v-for="(item, index) in msgList" :key="'user-' + index">
        <div class="q-loading" v-if="item.is_loading">
          <i class="el-icon-loading"></i>
        </div>
        <div class="message-bubble user-bubble">
          <div class="message-content">
            <VueMarkdown class="question-text" style="max-width: 352px; margin-right: 8px;" :source="item.content"
              :anchorAttributes="{ target: '_blank' }" :linkify="false" />
          </div>
        </div>
        <div class="message-avatar user-avatar-small">
          <i class="fas fa-user"></i>
        </div>
      </div>

      <!-- AI回复消息 -->
      <div class="message" v-if="!item.is_from_self" v-for="(item, index) in msgList" :key="'ai-' + index">
        <div class="ai-avatar-small">
          <img src="/img/avatar.jpg" alt="AI助手">
        </div>
        <div class="message-bubble ai-bubble">
          <div class="message-content">
            <div class="loading" v-if="item.loading_message">正在思考中</div>

            <!-- 回复主体 -->
            <VueMarkdown class="answer-text" :source="item.content" v-if="item.content" />

            <div v-show="item.is_final">
              <!-- 答案的底部操作栏 -->
              <div class="answer-option" v-show="item.showOption">
                <div class="answer-btn" @click="handlePlayAudio(item)">
                  <el-tooltip content="语音播报" trigger="hover">
                    <i class="fas fa-volume-up"></i>
                  </el-tooltip>
                </div>
                <div class="answer-btn" @click="copyContent(item)">
                  <el-tooltip content="复制" trigger="hover">
                    <i class="el-icon-copy-document"></i>
                  </el-tooltip>
                </div>
                <div class="answer-btn">
                  <el-tooltip content="该答案由AI助手生成，请谨慎甄别" trigger="hover">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </div>
                <div class="answer-btn">
                  <el-tooltip content="点赞" width="50" trigger="hover">
                    <img src="/img/avatar.jpg" width="16px" v-show="!item.hadUpThumbs"
                      @click="thumbsUp(item)">
                  </el-tooltip>
                </div>
                <div class="answer-btn">
                  <el-tooltip content="点踩" trigger="hover">
                    <img src="/img/avatar.jpg" width="13px" v-show="!item.hadDownThumbs"
                      @click="openFeedback(item)">
                  </el-tooltip>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 分割线 -->
        <el-divider v-if="item.start_new_conversation"
          :style="{ color: '#ccc', borderColor: '#ccc', padding: '0 16px' }">
          以下是新对话
        </el-divider>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <!-- 按钮组容器 -->
      <div class="btn-group">
        <div class="btn-group-left">
          <button class="action-btn" @click="bullhornPlayHandler">
            <i class="fas fa-volume-up" v-show="bullhornOpen"></i>
            <i class="fa-solid fa-volume-xmark" v-show="!bullhornOpen"></i>
            语音播报
          </button>
          <button class="action-btn" @click="phoneCallHandler">
            <i class="fas fa-phone-alt"></i> AI语音通话
          </button>
          <button class="action-btn" @click="onStopStream" v-show="answering">
            <i class="el-icon-video-pause"></i> 停止生成
          </button>
        </div>
        <div class="btn-group-right">
          <button class="action-btn" @click="clearChatHandler">
            <i class="fas fa-eraser"></i> 清除上下文
          </button>
        </div>
      </div>

      <div class="input-box">
        <button class="send-btn record-btn" @click="startRadios" v-show="recordState == 0">
          <i class="el-icon-microphone"></i>
        </button>
        <button class="send-btn record-btn record-btn1" @click="endRadios(true)" v-show="recordState == 1">
          <i class="el-icon-video-pause"></i>
        </button>
        <button class="send-btn record-btn" v-show="recordState == 2">
          <i class="el-icon-loading"></i>
        </button>
        <textarea v-model="question" :readonly="answering || isThinking" :placeholder="questionTip"
          @keyup.enter="onSendQuestion"></textarea>
        <button class="send-btn" @click="onSendQuestion" v-show="!answering">
          <i class="fas fa-paper-plane"></i>
        </button>
        <button class="send-btn" @click="onStopStream" v-show="answering">
          <i class="el-icon-video-pause"></i>
        </button>
      </div>
      <div class="tip">内容由AI生成，仅供参考</div>
    </div>

    <!-- 侧边栏（暂时保留原有结构，可后续移除） -->
    <div class="chat-sidebar" v-if="false">
      <div class="sidebar-header">
        <el-button type="primary" @click="createNewConversation" icon="el-icon-plus">
          新建对话
        </el-button>
      </div>

      <div class="conversation-list">
        <div
          v-for="conversation in conversations"
          :key="conversation.id"
          class="conversation-item"
          :class="{ active: currentConversationId === conversation.id }"
          @click="selectConversation(conversation.id)"
        >
          <div class="conversation-title">{{ conversation.title }}</div>
          <div class="conversation-time">{{ formatTime(conversation.lastMessageTime) }}</div>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click.stop="archiveConversation(conversation.id)"
            class="delete-btn"
          />
        </div>
      </div>
    </div>
    
  </div>
</template>

<script>
import clone from 'clone';
import VueMarkdown from 'vue-markdown';
import elementResizeDetectorMaker from 'element-resize-detector';
import {
  sendChatMessage,
  sendChatMessageStream,
  getConversations,
  getConversationMessages,
  archiveConversation,
  uploadFile
} from '@/api/ai/chat'
import { getToken } from '@/utils/auth'
import { getCurrentUserId } from '@/utils/userService'

export default {
  name: 'AiChat',
  components: {
    VueMarkdown
  },
  data() {
    return {
      // 原有数据保留部分
      conversations: [],
      currentConversationId: null,
      currentConversationTitle: 'AI助手',
      currentUserId: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/ai/chat/upload',
      currentStream: null,

      // 新增数据
      question: '', // 客户输入的问题
      inputFocus: false,
      answering: false, // 回答中
      isThinking: false, // 是否思考中
      bullhornOpen: false, // 全局语音开关
      isCalling: false,
      isWelcome: true, // 是否显示欢迎界面
      suggestionList: [{
        icon: 'fas fa-robot',
        name: '什么是人工智能？',
        value: '什么是人工智能？'
      }, {
        icon: 'fas fa-brain',
        name: '机器学习原理？',
        value: '机器学习原理？'
      }, {
        icon: 'fas fa-cog',
        name: '深度学习应用？',
        value: '深度学习应用？'
      }],
      recordTip: '语音输入（转文字）',
      RecordIns: null,
      startY: 0,
      moveY: 0,
      timeNum: 0,
      /** 录音状态，0-未开启，1-录制中，2-发送中 */
      recordState: 0,
      isRadiosShow: false,
      reqId: '',
      antiShake: false,
      pressPlayCount: 0,
      audioUrl: [],
      currentAudio: null,
      feedbackOpen: false,
      curFeedbackItem: null,
      isFeedbackLoading: false,
      feedbackList: [
        {
          id: '01',
          topic: '理解有误',
          options: [
            { id: '001', text: '答非所问' },
            { id: '002', text: '未理解要求' },
            { id: '003', text: '未理解上下文信息' },
          ]
        },
        {
          id: '02',
          topic: '答案存在错误',
          options: [
            { id: '001', text: '存在事实错误' },
            { id: '002', text: '存在逻辑错误' },
            { id: '003', text: '出现重复内容' },
            { id: '004', text: '格式/语法错误' },
            { id: '005', text: '内容不专业' },
            { id: '006', text: '系统报错' },
          ]
        },
        {
          id: '03',
          topic: '存在违法违规信息',
          options: [
            { id: '001', text: '存在违法信息' },
            { id: '002', text: '存在偏见与歧视' },
            { id: '003', text: '其他价值观问题' },
          ]
        }
      ],
      feedbackListSelected: [],
      timestampGap: 5 * 60, // 两次问题间隔大于5min，则展示时间戳
      msgList: [], // 对话消息列表
      newAnswerContent: '',//最新的消息内容
      answerContent: '',//用于临时保存消息
      speed: 30, // 毫秒/字符
      chunkSize: 1,  // 每次渲染字符数
      isTyping: false,
      chatsContent: [],
      type: null,
      is_final_number: null,//答案一共几个字
    };
  },
  computed: {
    questionTip() {
      let tip = this.answering ? '答案生成中...' : '请简要描述您的问题，避免出现具体事例和个人信息'
      if (this.recordState == 1) {
        tip = '语音录制中，请描述您的问题';
      } else if (this.recordState == 2) {
        tip = '正在识别语音内容...';
      }
      return tip;
    }
  },
  mounted() {
    this.initChat()
  },
  methods: {
    async initChat() {
      // 获取当前用户ID
      this.currentUserId = await getCurrentUserId()
      // 不显示欢迎界面，直接显示聊天界面
      this.isWelcome = false
    },

    // 新增方法
    /**
     * 发送问题
     */
    onSendQuestion() {
      console.log(this.question)
      if (!this.question.trim()) {
        
        this.$message.warning('不能发送空白消息哦')
        return;
      }

      // 如果正在生成答案，则停止
      if (this.answering) {
        this.onStopStream();
      }

      this.resetCursor();

      const msgContent = {
        request_id: this.getUUID(),
        content: this.question,
        is_from_self: true,
        timestamp: +new Date(),
        is_final: true, // 问题无流失，默认置为 true（即流式输出已结束）
        is_loading: false // 默认消息发送中
      };
      this.msgList.push(msgContent);
      this.sendQuestion(msgContent);
      this.isWelcome = false; // 隐藏欢迎界面
    },

    /**
     * 执行问题发出
     */
    sendQuestion(item) {
      console.log("发送消息:", item.content);
      this.answering = true;
      this.isThinking = true;
      this.question = '';

      // 调用原有的发送消息逻辑
      this.sendMessageToAI(item.content);
    },

    /**
     * 停止生成答案
     */
    onStopStream() {
      if (this.currentStream) {
        this.currentStream.cancel();
      }
      this.answering = false;
      this.isThinking = false;
    },

    /**
     * 清除上下文
     */
    clearChatHandler() {
      this.msgList = [];
      this.audioUrl = [];
      this.isWelcome = true;
    },

    /**
     * 自动播音开关
     */
    bullhornPlayHandler() {
      this.bullhornOpen = !this.bullhornOpen;
      if (this.bullhornOpen) {
        this.$message('自动播放已开启，再次点击可关闭播放')
      }
    },

    /**
     * 语音通话
     */
    phoneCallHandler() {
      this.isCalling = true;
      this.$message.info('语音通话功能开发中...');
    },

    /**
     * 根据参考提问
     */
    askByReference(question) {
      this.question = question;
      this.onSendQuestion();
    },

    /**
     * 语音播报处理
     */
    handlePlayAudio(item) {
      if (this.isCalling) {
        this.$message.warning('正在通话中')
        return;
      }
      this.$message.info('语音播报功能开发中...');
    },

    /**
     * 复制文本
     */
    copyContent(item) {
      let text = item.content;
      // 检查浏览器是否支持 Clipboard API
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text)
          .then(() => {
            this.$message.success('复制成功');
          })
          .catch(err => {
            this.$message.error('复制失败 ' + err);
          });
      } else {
        this.fallbackCopyText(text);
      }
    },

    // 不支持 Clipboard API 时使用备用方法
    fallbackCopyText(text) {
      // 创建临时textarea元素
      const textarea = document.createElement('textarea');
      textarea.value = text;
      textarea.style.position = 'fixed';  // 防止滚动到页面底部
      document.body.appendChild(textarea);
      textarea.select();

      try {
        // 执行复制命令
        const successful = document.execCommand('copy');
        if (successful) {
          this.$message.success('复制成功');
        } else {
          this.$message.error('复制失败');
        }
      } catch (err) {
        this.$message.error('复制失败 ' + err);
      }

      // 移除临时元素
      document.body.removeChild(textarea);
    },

    // 点赞
    thumbsUp(item) {
      this.$message.success('已点赞');
      item.hadUpThumbs = true;
      if (item.hadDownThumbs) {
        item.hadDownThumbs = false;
      }
    },

    // 点踩
    thumbsDown(item) {
      this.$message.success('已反馈');
      this.msgList.forEach(msg => {
        if (msg.request_id == item.request_id) {
          msg.hadDownThumbs = true;
          if (msg.hadUpThumbs) {
            msg.hadUpThumbs = false;
          }
        }
      })
      this.feedbackListSelected = []
      this.feedbackOpen = false
    },

    // 去反馈
    openFeedback(item) {
      this.feedbackOpen = true
      this.curFeedbackItem = item
    },

    // 提交反馈
    submitFeedback() {
      if (this.feedbackListSelected.length == 0) {
        this.$message.warning('请选择反馈内容')
        return
      }
      this.thumbsDown(this.curFeedbackItem)
    },

    /**
     * 语音录制相关方法
     */
    async startRadios() {
      this.recordState = 1;
      this.$message.success('语音录制中...');
      // 这里应该集成实际的录音功能
      setTimeout(() => {
        this.recordState = 0;
        this.$message.info('录音功能开发中...');
      }, 3000);
    },

    endRadios(isSend) {
      this.recordState = 0;
      if (isSend) {
        this.$message.info('语音识别功能开发中...');
      }
    },

    // 生成UUID
    getUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },

    // 重置游标
    resetCursor() {
      this.newAnswerContent = ''
      this.answerContent = ''
      this.chatsContent = [];
      this.type = null;
      this.is_final_number = null;
      this.isTyping = false;
    },

    /**
     * 发送消息到AI（复用原有的流式发送逻辑）
     */
    async sendMessageToAI(message) {
      if (this.isLoading) {
        return
      }

      this.isLoading = true

      // 添加AI消息占位符
      const aiMessage = {
        request_id: this.getUUID(),
        is_from_self: false,
        content: '',
        timestamp: +new Date(),
        is_final: false,
        loading_message: true,
        showOption: false,
        hadUpThumbs: false,
        hadDownThumbs: false
      }
      this.msgList.push(aiMessage)

      try {
        const requestData = {
          message: message,
          userId: this.currentUserId,
          conversationId: this.currentConversationId,
          createNewConversation: !this.currentConversationId
        }

        // 使用流式响应
        console.log('开始发送流式请求，requestData:', requestData)

        const stream = sendChatMessageStream(
          requestData,
          (data) => {
            console.log('收到流式数据:', data, '类型:', typeof data)
            if (typeof data === 'object' && data.type === 'conversation') {
              // 更新会话ID
              console.log('更新会话ID:', data.conversationId)
              this.currentConversationId = data.conversationId
            } else if (typeof data === 'string') {
              // 更新AI消息内容
              console.log('更新AI消息内容:', data)

              const messageIndex = this.msgList.findIndex(msg => msg.request_id === aiMessage.request_id)
              console.log('找到的消息索引:', messageIndex)

              if (messageIndex !== -1) {
                const currentContent = this.msgList[messageIndex].content
                const newContent = currentContent + data
                console.log('当前内容:', currentContent, '新内容:', newContent)

                // 使用Vue.set确保响应式更新
                this.$set(this.msgList[messageIndex], 'content', newContent)
                console.log('修改后的消息:', this.msgList[messageIndex])

                // 滚动到底部
                this.$nextTick(() => {
                  this.scrollToBottom()
                })
              } else {
                console.error('未找到对应的AI消息对象')
                console.error('当前所有消息ID:', this.msgList.map(m => m.request_id))
              }
            }
          },
          (error) => {
            console.error('流式响应错误:', error)
            this.$message.error('发送消息失败: ' + error.message)
            const messageIndex = this.msgList.findIndex(msg => msg.request_id === aiMessage.request_id)
            if (messageIndex !== -1) {
              this.$set(this.msgList[messageIndex], 'content', '发送失败: ' + error.message)
              this.$set(this.msgList[messageIndex], 'loading_message', false)
              this.$set(this.msgList[messageIndex], 'showOption', true)
            }
          },
          () => {
            console.log('流式响应完成')
            // 完成
            const messageIndex = this.msgList.findIndex(msg => msg.request_id === aiMessage.request_id)
            if (messageIndex !== -1) {
              this.$set(this.msgList[messageIndex], 'loading_message', false)
              this.$set(this.msgList[messageIndex], 'is_final', true)
              this.$set(this.msgList[messageIndex], 'showOption', true)
            }
            this.isWelcome = false;
          }
        )

        // 保存流对象以便取消
        this.currentStream = stream

      } catch (error) {
        this.$message.error('发送消息失败')
        console.error(error)
        const messageIndex = this.msgList.findIndex(msg => msg.request_id === aiMessage.request_id)
        if (messageIndex !== -1) {
          this.$set(this.msgList[messageIndex], 'content', '发送失败')
          this.$set(this.msgList[messageIndex], 'loading_message', false)
          this.$set(this.msgList[messageIndex], 'showOption', true)
        }
      } finally {
        this.isLoading = false
        this.answering = false
        this.isThinking = false
      }
    },

    // 原有的方法保留部分（简化版）
    async loadConversations() {
      try {
        const response = await getConversations(this.currentUserId)
        if (response.code === 200) {
          this.conversations = response.data || []
        }
      } catch (error) {
        console.error('加载会话列表失败', error)
      }
    },

    async selectConversation(conversationId) {
      this.currentConversationId = conversationId
      const conversation = this.conversations.find(c => c.id === conversationId)
      if (conversation) {
        this.currentConversationTitle = conversation.title
      }
      await this.loadMessages(conversationId)
    },

    async loadMessages(conversationId) {
      try {
        const response = await getConversationMessages(conversationId)
        if (response.code === 200) {
          this.msgList = response.data || []
          this.isWelcome = this.msgList.length === 0
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      } catch (error) {
        console.error('加载消息历史失败', error)
      }
    },

    beforeUpload(file) {
      const isValidType = file.type.startsWith('image/') ||
                         file.type.startsWith('text/') ||
                         file.type === 'application/pdf'
      if (!isValidType) {
        this.$message.error('只支持图片、文本和PDF文件')
        return false
      }

      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB')
        return false
      }

      return true
    },

    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.$message.success('文件上传成功')
      } else {
        this.$message.error(response.message || '文件上传失败')
      }
    },

    handleUploadError(error) {
      this.$message.error('文件上传失败')
      console.error(error)
    },

    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now - date

      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) { // 1天内
        return Math.floor(diff / 3600000) + '小时前'
      } else {
        return date.toLocaleDateString()
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = document.querySelector('.chat-messages')
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.chat-container {
  height: calc(100vh - 84px);
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f8f9fa;
}

.client-chat {
  background: #fff;
  border-radius: 8px;
  margin: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 欢迎界面样式 */
.header-bubble {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 20px;
}

.bubble-container {
  display: flex;
  align-items: center;
  gap: 20px;
  max-width: 800px;
}

.gif-container {
  flex-shrink: 0;
}

.gif-container img {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
}

.welcome-content {
  flex: 1;
}

.welcome-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.welcome-txt {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
}

.suggestions-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.suggestions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.suggestion {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: #f0f2f5;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.suggestion:hover {
  background: #e3f2fd;
  border-color: #2196f3;
  transform: translateY(-1px);
}

.suggestion i {
  color: #2196f3;
  font-size: 14px;
}

.suggestion div {
  font-size: 14px;
  color: #333;
}

/* 消息样式 */
.timestamp {
  font-weight: 400;
  font-size: 16px;
  line-height: 16px;
  text-align: center;
  color: #999;
  margin: 16px 0;
}

.message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.user-message {
  flex-direction: row-reverse;
}

.message-bubble {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
  word-wrap: break-word;
}

.user-bubble {
  background: #2196f3;
  color: white;
  margin-left: auto;
}

.ai-bubble {
  background: #f8f9fa;
  color: #333;
  border: 1px solid #e9ecef;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 10px;
  flex-shrink: 0;
}

.user-avatar-small {
  background: #2196f3;
  color: white;
}

.ai-avatar-small {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
}

.ai-avatar-small img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.message-content {
  flex: 1;
}

/* 加载状态 */
.q-loading {
  font-size: 24px;
  color: #999;
  padding: 20px 0px;
}

.loading {
  color: #999;
  font-size: 14px;
}

/* 答案操作栏 */
.answer-option {
  margin-bottom: 5px;
  margin-top: 10px;
  display: flex;
  justify-items: center;
  gap: 12px;
  flex-direction: row;
}

.answer-btn {
  cursor: pointer;
  display: flex;
  justify-items: center;
}

.answer-btn img {
  width: 16px;
  height: 16px;
}

/* 输入区域样式 */
.input-area {
  background: white;
  border-top: 1px solid #e6e6e6;
  padding: 20px;
}

.btn-group {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.btn-group-left,
.btn-group-right {
  display: flex;
  gap: 12px;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  color: #666;
  transition: all 0.2s;
}

.action-btn:hover {
  border-color: #2196f3;
  color: #2196f3;
}

.action-btn i {
  margin-right: 4px;
}

.input-box {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  position: relative;
}

.record-btn {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background: #f0f0f0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.record-btn:hover {
  background: #e0e0e0;
}

.record-btn1 {
  background: #ff4444;
  color: white;
}

.record-btn i {
  font-size: 16px;
}

.input-box textarea {
  flex: 1;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px 12px;
  resize: none;
  outline: none;
  font-family: inherit;
  transition: border-color 0.2s;
}

.input-box textarea:focus {
  border-color: #2196f3;
}

.send-btn {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background: #2196f3;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.send-btn:hover {
  background: #1976d2;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.send-btn i {
  font-size: 16px;
}

.tip {
  text-align: center;
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    height: 100vh;
  }

  .chat-messages {
    padding: 10px;
    margin: 10px;
  }

  .bubble-container {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .gif-container img {
    width: 80px;
    height: 80px;
  }

  .suggestions {
    justify-content: center;
  }

  .message-bubble {
    max-width: 85%;
  }

  .btn-group {
    flex-direction: column;
    gap: 8px;
  }

  .btn-group-left,
  .btn-group-right {
    justify-content: center;
  }
}
</style>
